<?php

namespace app\http\middleware;
use app\web\jwt\Jwts;
use think\facade\Cache;
use think\facade\Log;

class Auth
{
    public function handle($request, \Closure $next)
    {
        Log::info('请求参数：');
        Log::info(request()->param());
        Log::info('请求头：');
        Log::info(request()->header());
        /**
         * 验证token
         */
        $header = $request->header();
        if(!isset($header['authorization'])){
            return json(['data'=>[],'code'=>401],200);
        }
        $tokendata = explode(' ',$header['authorization']);
        if(!isset($tokendata[1])) return jsonp_error(401,'认证失败！');
        $token = $tokendata[1];
        $arr = Jwts::verifyToken($token);
        if(empty($arr)){
            return jsonp_error(401,'认证失败！');
        }
        if(!isset($arr['data']->userid)) return jsonp_error(401,'认证失败！');
        //设置登录信息
        session('user',$arr['data']->userid);
        if(isset($arr['data']->mac)) session('mac_info',$arr['data']->mac);
        return $next($request);
    }
}
